package com.hunlian.makelove.tuyaimage;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hunlian.makelove.R;
import com.hunlian.makelove.TakeCameraOrAlbum;
import com.hunlian.makelove.common.DisplayUtil;
import com.hunlian.makelove.view.CustomProgressDialog;
import com.hunlian.makelove.view.PaintSettingSView;
import com.hunlian.makelove.view.TextMoveLayout;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;

public class TuyaActivity extends Activity {

    private Button mBtnUndo,mBtnSave;
    private TuyaView mTuyaView;
    private LinearLayout mll;
    private RelativeLayout mRlContent;
    private ImageView mIvBg;
    private RelativeLayout mLl_title;
    private ImageButton mIbPen;
    private LinearLayout mLlBrushSize;
    //----------画笔--------------
    private SeekBar seekbar = null;
    private String mStartBrushSize = "1";
    private String mEndBrushSize = "30";
    private TextView mTvBrushSize, mTvStartBrushSize, mTvEndBrushSize;
    /**
     * 屏幕宽度
     */
    private int mScreenWidth;
    /**
     * 自定义随着拖动条一起移动的空间
     */
    private TextMoveLayout mTextMoveLayout;
    private ViewGroup.LayoutParams mLayoutParams;
    /**
     * 托动条的移动步调
     */
    private int moveStep = 1;
    /** 显示当前画笔宽度的TextView的宽度*/
    private int mBrushSizeWidth = 10;
    //----------------------------
    private int mTitleHeight;
    private String mPicPath;
    private String savePath;
    public static final int RESULT_SUCCESS = 0;
    public static final int RESULT_FAILED = 1;
    private static final String KEY = "path";

    private PaintSettingSView mPaintSettingSView;
    private CustomProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tuya_activity);

        mPicPath = getIntent().getStringExtra(KEY);
        savePath = getIntent().getStringExtra("savePath");

        mLl_title = (RelativeLayout) this.findViewById(R.id.ll_title);
        TextView mTvTitle = (TextView) mLl_title.findViewById(R.id.title);
        mTvTitle.setText("抹去重要信息");
        Button btnR = (Button) mLl_title.findViewById(R.id.btn_nav_right);
        btnR.setVisibility(View.GONE);

        //返回
        mIbPen = (ImageButton) mLl_title.findViewById(R.id.back);
        mIbPen.setVisibility(View.GONE);

        mLlBrushSize = (LinearLayout) this.findViewById(R.id.ll_brush_size);
        mLlBrushSize.setVisibility(View.GONE);

        //右按钮
        mIbPen = (ImageButton) mLl_title.findViewById(R.id.nav_right);
        mIbPen.setImageResource(R.drawable.toolbar_brush);
        mIbPen.setVisibility(View.VISIBLE);

        mIbPen.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mLlBrushSize.getVisibility()==View.GONE){
                    mLlBrushSize.setVisibility(View.VISIBLE);
                }else{
                    mLlBrushSize.setVisibility(View.GONE);
                }
            }

        });

        //seekbar
        mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mTvBrushSize = new TextView(this);
        mTvBrushSize.setBackgroundColor(Color.rgb(245, 245, 245));
        mTvBrushSize.setTextColor(Color.rgb(0, 161, 229));
        mTvBrushSize.setTextSize(16);
        mLayoutParams = new ViewGroup.LayoutParams(mScreenWidth, 50);
        mTextMoveLayout = (TextMoveLayout) findViewById(R.id.textLayout);
        mTextMoveLayout.addView(mTvBrushSize, mLayoutParams);
        mTvBrushSize.layout(0, 20, mScreenWidth, 80);
        /**
         * findView
         */
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        mTvStartBrushSize = (TextView) findViewById(R.id.start_time);
        mTvEndBrushSize = (TextView) findViewById(R.id.end_time);
        mPaintSettingSView = (PaintSettingSView) findViewById(R.id.sv_paint);
        mPaintSettingSView.setBrushWidth(mBrushSizeWidth);

        /**
         * setListener
         */
        seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListenerImp());
        searchVideos();


        mBtnUndo = (Button)findViewById(R.id.btn_return);
        mBtnSave = (Button)findViewById(R.id.btn_save);
        mll = (LinearLayout) findViewById(R.id.ll);
        mRlContent = (RelativeLayout) findViewById(R.id.rl_content);
        mIvBg = (ImageView)findViewById(R.id.iv_bg);

        LoadBitmapAsyncTask tast = new LoadBitmapAsyncTask(mPicPath,mIvBg);
        tast.execute();

        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();

        mTuyaView = new TuyaView(this,width,height);

        mll.addView(mTuyaView);

        mBtnUndo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTuyaView.undo();
            }
        });

        mBtnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLlBrushSize.setVisibility(View.GONE);
                progressDialog = CustomProgressDialog.createDialog(TuyaActivity.this,"正在加载中...");
                progressDialog.show();

/*                System.out.println("title top: " + mLl_title.getHeight());
                System.out.println("left: " + mll.getLeft());
                System.out.println("top: " + mll.getTop());
                System.out.println("right: " + mll.getRight());
                System.out.println("bottom: " + mll.getBottom());
                System.out.println("mRlContent: " + mRlContent.getTop());*/

                //new SavePhotoTask(mll.getLeft(), mll.getTop() + mLl_title.getHeight(), mll.getWidth(), mll.getHeight()).execute();

                saveWateredPhoto(mll.getLeft(), mll.getTop() + mLl_title.getHeight(), mll.getWidth(), mll.getHeight());
                if (progressDialog != null && progressDialog.isShowing()) {
                    try {
                        progressDialog.dismiss();
                        progressDialog = null;
                    } catch (Exception e) {
                    }
                }

                setResult(RESULT_OK);
                finish();
            }
        });
    }

    class SavePhotoTask extends AsyncTask<Void, Integer, Void>{

        int left,top,right,bottom;
        public SavePhotoTask(int left,int top,int right,int bottom){
            this.left = left;
            this.top = top;
            this.right = right;
            this.bottom = bottom;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... params) {
            saveWateredPhoto(left, top, right, bottom);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            if (progressDialog != null && progressDialog.isShowing()) {
                try {
                    progressDialog.dismiss();
                    progressDialog = null;
                } catch (Exception e) {
                }
            }
        }
    }


    private void searchVideos() {
        mTvStartBrushSize.setText(mStartBrushSize);
        mTvEndBrushSize.setText(mEndBrushSize);
        int progress = 10;
        mTvBrushSize.setText(progress + "");
        mBrushSizeWidth = (int)DisplayUtil.getTextWidth(this, progress + "",16)/2;
        seekbar.setEnabled(true);
        seekbar.setMax(Integer.valueOf(mEndBrushSize) - 1);
        seekbar.setProgress(progress);
        int marginLeft = seekbar.getPaddingLeft();
        moveStep = (int) (((mScreenWidth - 2*marginLeft)/ (float) Integer.valueOf(mEndBrushSize)));
        mTvBrushSize.layout((int) (progress * moveStep)+mBrushSizeWidth, 20, mScreenWidth, 80);
    }

    /**

     * 加载本地图片

     * http://bbs.3gstdy.com

     * @param url

     * @return

     */

    private  Bitmap getLoacalBitmap(String url) {

        try {

            FileInputStream fis = new FileInputStream(url);

            return BitmapFactory.decodeStream(fis);

        } catch (FileNotFoundException e) {

            e.printStackTrace();

            return null;

        }

    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

/*    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){


            Rect statusBarRect = new Rect();
            this.getWindow().getDecorView().getWindowVisibleDisplayFrame(statusBarRect);

            int titleHeight = this.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
            mTitleHeight =  statusBarRect.top+titleHeight;
            System.out.println("statusBarRect: " + statusBarRect.top);
            System.out.println("titleRect: " + titleHeight);
        }
    }*/


    /**截取包含水印的照片*/
    private boolean saveWateredPhoto(int left,int top,int width,int height) {


        View view = getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();

        if(width<=0 || height <=0){
            //图片尺寸太小
            return false;
        }

        Bitmap bmp = Bitmap.createBitmap(bitmap,left,top,width,height);

        saveBitmap(savePath,bmp);

        view.setDrawingCacheEnabled(false);
        bmp.recycle();
        return true;
    }

    /** 保存方法 */
    public void saveBitmap(String picName,Bitmap bm) {

        File f = new File(picName);
        if (!f.exists()) {
            //f.delete();

            try {
                if(!new File(f.getParent()).exists()) {
                    new File(f.getParent()).mkdirs();
                }
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *此异步类用来加载要涂鸦的图片，因为加载图片是一个耗时的操作，因此
     * 采用此类来实现
     *@author zealjiang
     *@time 2016/5/31 17:59
     */
    class LoadBitmapAsyncTask extends AsyncTask<String,Integer, Bitmap> {

        private ImageView imageView;
        private String filePath;

        public LoadBitmapAsyncTask(String filePath, ImageView imageView) {
            this.filePath = filePath;
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {

            //Bitmap bitmap = getLoacalBitmap(mPicPath); //从本地取图片
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);

            SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(bitmap);
            if(softReference==null){
                TakeCameraOrAlbum takeCameraOrAlbum = new TakeCameraOrAlbum();
                bitmap = takeCameraOrAlbum.picFileToBitmap(filePath);

            }else{
                bitmap =  softReference.get();
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            imageView.setImageBitmap(bitmap);
        }
    }


    private class OnSeekBarChangeListenerImp implements
            SeekBar.OnSeekBarChangeListener {

        // 触发操作，拖动
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            mTvBrushSize.layout((int) (progress * moveStep) + mBrushSizeWidth, 20, mScreenWidth, 80);
            mTvBrushSize.setText((progress + 1) + "");

            if(mTuyaView!=null) {
                mTuyaView.setPaintSize(progress + 1);
            }

            mPaintSettingSView.setBrushWidth(progress + 1);
        }

        // 表示进度条刚开始拖动，开始拖动时候触发的操作
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        // 停止拖动时候
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }
}
